# encoding:utf-8
import datetime
import logging
from urllib import unquote
from django.shortcuts import render_to_response, get_object_or_404
from django.http import HttpResponseRedirect, Http404, HttpResponsePermanentRedirect
from django.core.paginator import Paginator, EmptyPage, InvalidPage
from django.template import RequestContext
from django import template
from django.utils.html import *
from django.db.models import Q, Count
from django.utils.translation import ugettext as _
from django.core.urlresolvers import reverse
from django.template.defaultfilters import slugify
from django.utils.safestring import mark_safe

from forum import settings as django_settings
from forum.utils.html import hyperlink
from forum.utils.diff import textDiff as htmldiff
from forum.utils import pagination
from forum.forms import *
from forum.models import *
from forum.models.node import NodeQuerySet
from forum.actions import IssueViewAction, ArgumentViewAction
from forum.http_responses import HttpResponseUnauthorized
from forum.feed import RssIssueFeed, RssReasonFeed, RssArgumentFeed, RssRebuttalFeed
from forum.utils.pagination import generate_uri

import decorators

class HottestArgumentsSort(pagination.SortBase):
    def apply(self, arguments):
        return arguments.annotate(new_child_count=Count('all_children')).filter(
                all_children__added_at__gt=datetime.datetime.now() - datetime.timedelta(days=1)).order_by('-new_child_count')


class HottestIssuesSort(pagination.SortBase):
    def apply(self, arguments):
        return issues.annotate(new_child_count=Count('all_children')).filter(
                all_children__added_at__gt=datetime.datetime.now() - datetime.timedelta(days=1)).order_by('-new_child_count')


class ArgumentListPaginatorContext(pagination.PaginatorContext):
    def __init__(self, id='QUESTIONS_LIST', prefix='', pagesizes=(15, 30, 50), default_pagesize=30):
        super (ArgumentListPaginatorContext, self).__init__(id, sort_methods=(
            (_('active'), pagination.SimpleSort(_('active'), '-last_activity_at', _("Most <strong>recently updated</strong> arguments"))),
            (_('newest'), pagination.SimpleSort(_('newest'), '-added_at', _("most <strong>recently proposed</strong> arguments"))),
            (_('hottest'), HottestArgumentsSort(_('hottest'), _("most <strong>active</strong> arguments in the last 24 hours</strong>"))),
            (_('mostvoted'), pagination.SimpleSort(_('most voted'), '-score', _("most <strong>voted</strong> arguments"))),
        ), pagesizes=pagesizes, default_pagesize=default_pagesize, prefix=prefix)


class IssueListPaginatorContext(pagination.PaginatorContext):
    def __init__(self, id='ISSUES_LIST', prefix='', pagesizes=(15, 30, 50), default_pagesize=30):
        super (IssueListPaginatorContext, self).__init__(id, sort_methods=(
            (_('active'), pagination.SimpleSort(_('active'), '-last_activity_at', _("Most <strong>recently updated</strong> issues"))),
            (_('newest'), pagination.SimpleSort(_('newest'), '-added_at', _("most <strong>recently proposed</strong> issues"))),
            (_('hottest'), HottestIssuesSort(_('hottest'), _("most <strong>active</strong> issues in the last 24 hours</strong>"))),
            (_('mostvoted'), pagination.SimpleSort(_('most voted'), '-score', _("most <strong>voted</strong> issues"))),
        ), pagesizes=pagesizes, default_pagesize=default_pagesize, prefix=prefix)

class RebuttalSort(pagination.SimpleSort):
    def apply(self, rebuttals):
        assert type(rebuttals)==NodeQuerySet, 'rebuttals has type of %s'%type(rebuttals)
        if not settings.DISABLE_ACCEPTING_FEATURE:
            return rebuttals.order_by(*(['-marked'] + list(self._get_order_by())))
        else:
            return super(RebuttalSort, self).apply(rebuttals)

class RebuttalPaginatorContext(pagination.PaginatorContext):
    def __init__(self, id='ANSWER_LIST', prefix='', default_pagesize=10):
        super (RebuttalPaginatorContext, self).__init__(id, sort_methods=(
            (_('oldest'), RebuttalSort(_('oldest rebuttals'), 'added_at', _("oldest rebuttals will be shown first"))),
            (_('newest'), RebuttalSort(_('newest rebuttals'), '-added_at', _("newest rebuttals will be shown first"))),
            (_('votes'), RebuttalSort(_('popular rebuttals'), ('-score', 'added_at'), _("most voted rebuttals will be shown first"))),
        ), default_sort=_('votes'), pagesizes=(5, 10, 20), default_pagesize=default_pagesize, prefix=prefix)

class ReasonSort(pagination.SimpleSort):
    def apply(self, reasons):
        assert type(reasons)==NodeQuerySet, 'reasons has type of %s'%type(reasons)
        if not settings.DISABLE_ACCEPTING_FEATURE:
            return reasons.order_by(*(['-marked'] + list(self._get_order_by())))
        else:
            return super(ReasonSort, self).apply(reasons)

class ReasonPaginatorContext(pagination.PaginatorContext):
    def __init__(self, id='PROCON_LIST', prefix='', default_pagesize=10):
        super (ReasonPaginatorContext, self).__init__(id, sort_methods=(
            (_('oldest'), ReasonSort(_('oldest'), 'added_at', _("oldest first"))),
            (_('newest'), ReasonSort(_('newest'), '-added_at', _("newest first"))),
            (_('votes'), ReasonSort(_('most popular'), ('-score', 'added_at'), _("most voted first"))),
        ), default_sort=_('votes'), pagesizes=(5, 10, 20), default_pagesize=default_pagesize, prefix=prefix)

class TagPaginatorContext(pagination.PaginatorContext):
    def __init__(self):
        super (TagPaginatorContext, self).__init__('TAG_LIST', sort_methods=(
            (_('name'), pagination.SimpleSort(_('by name'), 'name', _("sorted alphabetically"))),
            (_('used'), pagination.SimpleSort(_('by popularity'), '-used_count', _("sorted by frequency of tag use"))),
        ), default_sort=_('used'), pagesizes=(30, 60, 120))
    
def issues_feed(request):
    return RssIssueFeed(
                request,
                Issue.objects.filter_state(deleted=False).order_by('-last_activity_at'),
                settings.APP_TITLE + _(' - ')+ _('latest arguments'),
                settings.APP_DESCRIPTION)(request)


def arguments_feed(request):
    return RssArgumentFeed(
                request,
                Argument.objects.filter_state(deleted=False).order_by('-last_activity_at'),
                settings.APP_TITLE + _(' - ')+ _('latest arguments'),
                settings.APP_DESCRIPTION)(request)

@decorators.render('index.html')
def index(request):
    issues = Issue.objects.filter_state(deleted=False,published=True)
    paginator_context = IssueListPaginatorContext()
    paginator_context.base_path = reverse('issues')
    return issue_list(request,
                         issues,
                         base_path=reverse('issues'),
                         feed_url=reverse('latest_issues_feed'),
                         paginator_context=paginator_context)

#@decorators.render('arguments.html', 'unrebuttaled', _('unrebuttaled'), weight=400)
#def unrebuttaled(request):
#    return argument_list(request,
#                         Argument.objects.exclude(id__in=Argument.objects.filter(children__marked=True).distinct()).exclude(marked=True),
#                         _('open arguments without an accepted rebuttal'),
#                         None,
#                         _("Unrebuttaled Arguments"))

# weight determines the order of the tabs

@decorators.render('issues.html', 'issues', _('issues'), weight=0)
def issues(request):
    issues = Issue.objects.filter_state(deleted=False,published=True)
    return issue_list(request, issues, _('issues'))

@decorators.render('arguments.html', 'arguments', _('arguments'), weight=5)
def arguments(request):
    arguments = Argument.objects.filter_state(deleted=False,published=True)
    return argument_list(request, arguments, _('arguments'))

@decorators.render('arguments.html', 'drafts', _('drafts'), weight=10)
def drafts(request):
    arguments = Argument.objects.filter(author=request.user) # can we assume user is authenticated by now?
    return argument_list(request, 
                         arguments.filter_state(deleted=False,published=False), _('drafts'),
                         page_title=_("Your Drafts")
                        )

@decorators.render('arguments.html')
def tag(request, tag):
    try:
        tag = Tag.active.get(name=unquote(tag))
    except Tag.DoesNotExist:
        raise Http404

    # Getting the arguments QuerySet
    arguments = Argument.objects.filter(tags__id=tag.id)

    if request.method == "GET":
        user = request.GET.get('user', None)

        if user is not None:
            try:
                arguments = arguments.filter(author=User.objects.get(username=user))
            except User.DoesNotExist:
                raise Http404

    # The extra tag context we need to pass
    tag_context = {
        'tag' : tag,
    }

    # The context returned by the argument_list function, contains info about the arguments
    argument_context = argument_list(request,
                         arguments,
                         mark_safe(_(u'arguments tagged <span class="tag">%(tag)s</span>') % {'tag': tag}),
                         None,
                         mark_safe(_(u'Arguments Tagged With %(tag)s') % {'tag': tag}),
                         False)

    # If the return data type is not a dict just return it
    if not isinstance(argument_context, dict):
        return argument_context

    argument_context = dict(argument_context)

    # Create the combined context
    context = dict(argument_context.items() + tag_context.items())

    return context

@decorators.render('issues.html')
def issue_tag(request, tag):
    try:
        tag = Tag.active.get(name=unquote(tag))
    except Tag.DoesNotExist:
        raise Http404

    # Getting the arguments QuerySet
    issues = Issue.objects.filter(tags__id=tag.id)

    if request.method == "GET":
        user = request.GET.get('user', None)

        if user is not None:
            try:
                issues = issues.filter(author=User.objects.get(username=user))
            except User.DoesNotExist:
                raise Http404

    # The extra tag context we need to pass
    tag_context = {
        'tag' : tag,
    }

    # The context returned by the argument_list function, contains info about the arguments
    issue_context = issue_list(request,
                         issues,
                         mark_safe(_(u'issues tagged <span class="tag">%(tag)s</span>') % {'tag': tag}),
                         None,
                         mark_safe(_(u'Issues Tagged With %(tag)s') % {'tag': tag}),
                         False)

    # If the return data type is not a dict just return it
    if not isinstance(issue_context, dict):
        return issue_context

    issue_context = dict(issue_context)

    # Create the combined context
    context = dict(issue_context.items() + tag_context.items())

    return context

@decorators.render('arguments.html', 'arguments', tabbed=False)
def user_arguments(request, mode, user, slug):
    user = get_object_or_404(User, id=user)

    if mode == _('asked-by'):
        arguments = Argument.objects.filter(author=user)
        description = _("Arguments proposed by %s")
    elif mode == _('rebuttaled-by'):
        arguments = Argument.objects.filter(children__author=user, children__node_type='rebuttal').distinct()
        description = _("Arguments rebuttaled by %s")
    elif mode == _('subscribed-by'):
        if not (request.user.is_superuser or request.user == user):
            return HttpResponseUnauthorized(request)
        arguments = user.subscriptions

        if request.user == user:
            description = _("Arguments you subscribed %s")
        else:
            description = _("Arguments subscribed by %s")
    else:
        raise Http404


    return argument_list(request, arguments,
                         mark_safe(description % hyperlink(user.get_profile_url(), user.username)),
                         page_title=description % user.username)

def issue_list(request, initial,
                  list_description=_('issues'),
                  base_path=None,
                  page_title=_("All Issues"),
                  allowIgnoreTags=True,
                  feed_url=None,
                  paginator_context=None,
                  feed_sort=('-added_at',),
                  feed_req_params_exclude=(_('page'), _('pagesize'), _('sort')),
                  extra_context={}):

    issues = initial.filter_state(deleted=False)

    if request.user.is_authenticated() and allowIgnoreTags:
        issues = issues.filter(~Q(tags__id__in = request.user.marked_tags.filter(user_selections__reason = 'bad')))

    if page_title is None:
        page_title = _("Arguments")

    if request.GET.get('type', None) == 'rss':
        if feed_sort:
            issues = issues.order_by(*feed_sort)
        return RssIssueFeed(request, issues, page_title, list_description)(request)

    keywords =  ""
    if request.GET.get("q"):
        keywords = request.GET.get("q").strip()

    #rebuttal_count = Rebuttal.objects.filter_state(deleted=False).filter(parent__in=arguments).count()
    #rebuttal_description = _("rebuttals")

    if not feed_url:
        req_params = generate_uri(request.GET, feed_req_params_exclude)

        if req_params:
            req_params = '&' + req_params

        feed_url = request.path + "?type=rss" + req_params

    context = {
        'issues' : issues.distinct(),
        'issues_count' : issues.count(),
        'keywords' : keywords,
        'list_description': list_description,
        'base_path' : base_path,
        'page_title' : page_title,
        'tab' : 'issues',
        'feed_url': feed_url,
    }
    context.update(extra_context)

    return pagination.paginated(request,
                               ('issues', paginator_context or IssueListPaginatorContext()), context)



def argument_list(request, initial,
                  list_description=_('arguments'),
                  base_path=None,
                  page_title=_("All Arguments"),
                  allowIgnoreTags=True,
                  feed_url=None,
                  paginator_context=None,
                  feed_sort=('-added_at',),
                  feed_req_params_exclude=(_('page'), _('pagesize'), _('sort')),
                  extra_context={}):

    arguments = initial.filter_state(deleted=False)

    if request.user.is_authenticated() and allowIgnoreTags:
        arguments = arguments.filter(~Q(tags__id__in = request.user.marked_tags.filter(user_selections__reason = 'bad')))

    if page_title is None:
        page_title = _("Arguments")

    if request.GET.get('type', None) == 'rss':
        if feed_sort:
            arguments = arguments.order_by(*feed_sort)
        return RssArgumentFeed(request, arguments, page_title, list_description)(request)

    keywords =  ""
    if request.GET.get("q"):
        keywords = request.GET.get("q").strip()

    #rebuttal_count = Rebuttal.objects.filter_state(deleted=False).filter(parent__in=arguments).count()
    #rebuttal_description = _("rebuttals")

    if not feed_url:
        req_params = generate_uri(request.GET, feed_req_params_exclude)

        if req_params:
            req_params = '&' + req_params

        feed_url = request.path + "?type=rss" + req_params

    context = {
        'arguments' : arguments.distinct(),
        'arguments_count' : arguments.count(),
        'keywords' : keywords,
        'list_description': list_description,
        'base_path' : base_path,
        'page_title' : page_title,
        'tab' : 'arguments',
        'feed_url': feed_url,
    }
    context.update(extra_context)

    return pagination.paginated(request,
                               ('arguments', paginator_context or ArgumentListPaginatorContext()), context)


def search(request):
    if request.method == "GET" and "q" in request.GET:
        keywords = request.GET.get("q")
        search_type = request.GET.get("t")

        if not keywords:
            return HttpResponseRedirect(reverse(index))
        if search_type == 'tag':
            return HttpResponseRedirect(reverse('tags') + '?q=%s' % urlquote(keywords.strip()))
        elif search_type == "user":
            return HttpResponseRedirect(reverse('users') + '?q=%s' % urlquote(keywords.strip()))
        else:
            return argument_search(request, keywords)
    else:
        return render_to_response("search.html", context_instance=RequestContext(request))

@decorators.render('arguments.html')
def argument_search(request, keywords):
    rank_feed = False
    can_rank, initial = Argument.objects.search(keywords)

    if can_rank:
        sort_order = None

        if isinstance(can_rank, basestring):
            sort_order = can_rank
            rank_feed = True

        paginator_context = ArgumentListPaginatorContext()
        paginator_context.sort_methods[_('ranking')] = pagination.SimpleSort(_('relevance'), sort_order, _("most relevant arguments"))
        paginator_context.force_sort = _('ranking')
    else:
        paginator_context = None

    feed_url = mark_safe(escape(request.path + "?type=rss&q=" + keywords))

    return argument_list(request, initial,
                         _("arguments matching '%(keywords)s'") % {'keywords': keywords},
                         None,
                         _("arguments matching '%(keywords)s'") % {'keywords': keywords},
                         paginator_context=paginator_context,
                         feed_url=feed_url, feed_sort=rank_feed and (can_rank,) or '-added_at')


@decorators.render('tags.html', 'tags', _('tags'), weight=100)
def tags(request):
    stag = ""
    tags = Tag.active.all()

    if request.method == "GET":
        stag = request.GET.get("q", "").strip()
        if stag:
            tags = tags.filter(name__icontains=stag)

    return pagination.paginated(request, ('tags', TagPaginatorContext()), {
        "tags" : tags,
        "stag" : stag,
        "keywords" : stag
    })

def update_argument_view_times(request, argument):
    last_seen_in_argument = request.session.get('last_seen_in_argument', {})

    last_seen = last_seen_in_argument.get(argument.id, None)

    if (not last_seen) or (last_seen < argument.last_activity_at):
        ArgumentViewAction(argument, request.user, ip=request.META['REMOTE_ADDR']).save()
        last_seen_in_argument[argument.id] = datetime.datetime.now()
        request.session['last_seen_in_argument'] = last_seen_in_argument

def update_issue_view_times(request, issue):
    last_seen_in = request.session.get('last_seen_in_issue', {})

    last_seen = last_seen_in.get(issue.id, None)

    if (not last_seen) or (last_seen < issue.last_activity_at):
        IssueViewAction(issue, request.user, ip=request.META['REMOTE_ADDR']).save()
        last_seen_in[issue.id] = datetime.datetime.now()
        request.session['last_seen_in_issue'] = last_seen_in

def match_argument_slug(id, slug):
    slug_words = slug.split('-')
    qs = Argument.objects.filter(title__istartswith=slug_words[0])

    for q in qs:
        if slug == urlquote(slugify(q.title)):
            return q

    return None

def rebuttal_redirect(request, rebuttal):
    pc = RebuttalPaginatorContext()

    sort = pc.sort(request)

    if sort == _('oldest'):
        filter = Q(added_at__lt=rebuttal.added_at)
    elif sort == _('newest'):
        filter = Q(added_at__gt=rebuttal.added_at)
    elif sort == _('votes'):
        filter = Q(score__gt=rebuttal.score) | Q(score=rebuttal.score, added_at__lt=rebuttal.added_at)
    else:
        raise Http404()

    count = rebuttal.argument.rebuttals.filter(Q(marked=True) | filter).exclude(state_string="(deleted)").count()
    pagesize = pc.pagesize(request)

    page = count / pagesize
    
    if count % pagesize:
        page += 1
        
    if page == 0:
        page = 1

    return HttpResponseRedirect("%s?%s=%s&focusedRebuttalId=%s#%s" % (
        rebuttal.argument.get_absolute_url(), _('page'), page, rebuttal.id, rebuttal.id))

@decorators.render("argument.html", 'arguments')
def argument(request, id, slug='', rebuttal=None):
    try:
        argument = Argument.objects.get(id=id)
    except:
        if slug:
            argument = match_argument_slug(id, slug)
            if argument is not None:
                return HttpResponseRedirect(argument.get_absolute_url())

        raise Http404()

    if argument.nis.deleted and not request.user.can_view_deleted_post(argument):
        raise Http404

    if not argument.nis.published and request.user != argument.author:
        raise Http404

    if request.GET.get('type', None) == 'rss':
        return RssRebuttalFeed(request, argument, include_comments=request.GET.get('comments', None) == 'yes')(request)

    if rebuttal:
        rebuttal = get_object_or_404(Rebuttal, id=rebuttal)

        if (argument.nis.deleted and not request.user.can_view_deleted_post(argument)) or rebuttal.argument != argument:
            raise Http404

        if rebuttal.marked:
            return HttpResponsePermanentRedirect(argument.get_absolute_url())

        return rebuttal_redirect(request, rebuttal)

    if settings.FORCE_SINGLE_URL and (slug != slugify(argument.title)):
        return HttpResponsePermanentRedirect(argument.get_absolute_url())

    if request.POST:
        rebuttal_form = RebuttalForm(request.POST, user=request.user)
    else:
        rebuttal_form = RebuttalForm(user=request.user)

    rebuttals = request.user.get_visible_rebuttals(argument)

    update_argument_view_times(request, argument)

    if request.user.is_authenticated():
        try:
            subscription = ArgumentSubscription.objects.get(argument=argument, user=request.user)
        except:
            subscription = False
    else:
        subscription = False
    try:
        focused_rebuttal_id = int(request.GET.get("focusedRebuttalId", None))
    except TypeError, ValueError:
        focused_rebuttal_id = None

    #assert type(rebuttals.iterator().next())==NodeQuerySet, \
    #    "rebuttals is of type %s"%(type(rebuttals.iterator().next()))

#    assert False, 'types are %s,%s,%s,%s,%s,%s'%(
#        type(argument),
#        type(rebuttal_form),
#        type(rebuttals),
#        type(argument.get_related_arguments()),
#        type(subscription),
#        type(focused_rebuttal_id))

    return pagination.paginated(request, ('rebuttals', RebuttalPaginatorContext()), {
    "argument" : argument,
    "node" : argument,
    "rebuttal" : rebuttal_form,
    "rebuttals" : rebuttals,
    "similar_arguments" : argument.get_related_arguments(),
    "subscription": subscription,
    "embed_youtube_videos" : settings.EMBED_YOUTUBE_VIDEOS,
    "focused_rebuttal_id" : focused_rebuttal_id
    })


@decorators.render("issue.html", 'issues')
def issue(request, id, slug='', reason=None):
    try:
        issue = Issue.objects.get(id=id)
    except:
        if slug:
            issue = match_issue_slug(id, slug)
            if issue is not None:
                return HttpResponseRedirect(issue.get_absolute_url())

        raise Http404()

    if issue.nis.deleted and not request.user.can_view_deleted_post(issue):
        raise Http404

    if not issue.nis.published and request.user != issue.author:
        raise Http404

    if request.GET.get('type', None) == 'rss':
        return RssReasonFeed(request, issue, include_comments=request.GET.get('comments', None) == 'yes')(request)

    if reason:
        reason = get_object_or_404(Reason, id=reason)

        if (issue.nis.deleted and not request.user.can_view_deleted_post(issue)) or reason.issue != issue:
            raise Http404

        if reason.marked:
            return HttpResponsePermanentRedirect(issue.get_absolute_url())

        return reason_redirect(request, reason)

    if settings.FORCE_SINGLE_URL and (slug != slugify(issue.title)):
        return HttpResponsePermanentRedirect(issue.get_absolute_url())

    if request.POST:
        reason_form = ReasonForm(request.POST, user=request.user)
    else:
        reason_form = ReasonForm(user=request.user)

    positions = Position.objects.filter(parent=issue)
    pro_position = positions.get(title='pro')
    pros = request.user.get_visible_reasons(pro_position)
    con_position = positions.get(title='con')
    cons = request.user.get_visible_reasons(con_position)

    update_issue_view_times(request, issue)

    if request.user.is_authenticated():
        try:
            subscription = IssueSubscription.objects.get(issue=issue, user=request.user)
        except:
            subscription = False
    else:
        subscription = False
    try:
        focused_reason_id = int(request.GET.get("focusedReasonId", None))
    except TypeError, ValueError:
        focused_reason_id = None

    return pagination.paginated(request, [
        ('pros', ReasonPaginatorContext()),
        ('cons', ReasonPaginatorContext()),
    ] , {
        "issue" : issue,
        "node" : issue,
        "reason" : reason_form,
        "pro_position" : pro_position,
        "con_position" : con_position,
        "pros" : pros,
        "cons" : cons,
        "similar_issues" : issue.get_related_issues(),
        "subscription": subscription,
        "embed_youtube_videos" : settings.EMBED_YOUTUBE_VIDEOS,
        "focused_reason_id" : focused_reason_id
    })


REVISION_TEMPLATE = template.loader.get_template('node/revision.html')

def revisions(request, id):
    post = get_object_or_404(Node, id=id).leaf
    revisions = list(post.revisions.order_by('revised_at'))
    rev_ctx = []

    for i, revision in enumerate(revisions):
        rev_ctx.append(dict(inst=revision, html=template.loader.get_template('node/revision.html').render(template.Context({
        'title': revision.title,
        'html': revision.html,
        'tags': revision.tagname_list(),
        }))))

        if i > 0:
            rev_ctx[i]['diff'] = mark_safe(htmldiff(rev_ctx[i-1]['html'], rev_ctx[i]['html']))
        else:
            rev_ctx[i]['diff'] = mark_safe(rev_ctx[i]['html'])

        if not (revision.summary):
            rev_ctx[i]['summary'] = _('Revision n. %(rev_number)d') % {'rev_number': revision.revision}
        else:
            rev_ctx[i]['summary'] = revision.summary

    rev_ctx.reverse()

    return render_to_response('revisions.html', {
    'post': post,
    'revisions': rev_ctx,
    }, context_instance=RequestContext(request))



